package com.beiing.tianshuai.tianshuai.message.ui;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.NewFriendAdapter;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.CommonBean;
import com.beiing.tianshuai.tianshuai.entity.NewFriendMessageBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.message.presenter.NewFriendMessagePresenter;
import com.beiing.tianshuai.tianshuai.message.view.NewFriendMessageViewImpl;
import com.beiing.tianshuai.tianshuai.mine.ui.PersonalDataCardActivity;
import com.beiing.tianshuai.tianshuai.rx.MsgEvent;
import com.beiing.tianshuai.tianshuai.rx.RxBus;
import com.beiing.tianshuai.tianshuai.service.EasemobService;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.SPUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.widget.RecycleViewDivider;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class NewFriendMessageActivity extends BaseActivity implements NewFriendMessageViewImpl {

    private static final String                         TAG = "NewFriendMessage";
    private Unbinder                                    mUnbinder;
    private Context                                     mContext;
    private NewFriendAdapter                            mAdapter;
    private NewFriendMessagePresenter                   mPresenter;
    /**
     * 绑定视图
     */
    @BindView(R.id.txt_empty_warning)
    TextView mEmptyWarning;
    @BindView(R.id.toolbar_iv_back)
    ImageView mToolbarIvBack;
    @BindView(R.id.toolbar_tv_title)
    TextView mToolbarTvTitle;
    @BindView(R.id.rv_new_friend_message_list)
    RecyclerView mRvList;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_new_friend_message;
    }

    @Override
    protected void init() {
        mUnbinder = ButterKnife.bind(this);
        mContext = this;
        initToolbar();
        initRecyclerView();
        initPresenter();
        initListener();
        SPUtils.put(getApplicationContext(), "newFriendCount", 0);
        EasemobService.newFriendNum = 0;
    }

    /**
     * 初始化Toolbar
     */
    private void initToolbar() {
        mToolbarIvBack.setVisibility(View.VISIBLE);
        mToolbarTvTitle.setText("好友请求");
    }

    /**
     * 监听事件
     */
    private void initListener() {
        // Adapter
        mAdapter.setListener(new NewFriendAdapter.OnItemClickListener() {
            @Override
            public void onAgreeClick(String id, String fromId, String toId) {
                mPresenter.getAgreeAddFriend(id, fromId, toId);
            }

            @Override
            public void onRefuseClick(String id, String fromId, String toId) {
                mPresenter.getRefuseAddFriend(id, fromId, toId);
            }

            @Override
            public void onItemClick(String id, String fromId, String toId) {
                Intent intent = new Intent(mContext, PersonalDataCardActivity.class);
                intent.putExtra("uid", fromId);
                startActivity(intent);
            }
        });

        // 返回
        mToolbarIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void initRecyclerView() {
        mAdapter = new NewFriendAdapter(mContext);
        mRvList.setAdapter(mAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        mRvList.setNestedScrollingEnabled(false);
        mRvList.setLayoutManager(linearLayoutManager);
        //绘制item间的分割线，
        mRvList.addItemDecoration(
                new RecycleViewDivider(
                        mContext, LinearLayoutManager.HORIZONTAL, 1,
                        ContextCompat.getColor(mContext, R.color.textColorGrayDark))
        );
    }

    private void initPresenter() {
        if (mPresenter == null) {
            mPresenter = new NewFriendMessagePresenter(this);
        }
        mPresenter.getNewFriendMessage(UserInfoBean.getUid(mContext));
        mPresenter.consumeNewFriendsMarks(UserInfoBean.getUid(mContext));
    }

    @Override
    protected void onResume() {
        SPUtils.put(mContext, "newFriendCount", 0);
        RxBus.getInstanceBus().post(new MsgEvent<>("messageNotice", 0));
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
    }

    @Override
    public void showProgress() {
        CustomProgressDialog.showLoading(mContext, "正在努力加载，请稍后...", true);
    }

    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }

    @Override
    public void onRequestSuccess(NewFriendMessageBean bean) {
        List<NewFriendMessageBean.DataBean.NumberBean> messages = bean.getData().getNumber();
        if (messages.size() > 0) {
            LogUtils.i(messages.toString(), TAG);
            mAdapter.clearData();
            mAdapter.appendData(messages);
            if (mEmptyWarning != null) {
                mEmptyWarning.setVisibility(View.GONE);
            }
        } else {
            if (mEmptyWarning != null) {
                mEmptyWarning.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        showShortText("网络异常");
    }

    @Override
    public void getRefuse(CommonBean bean, final String fromId) {
        int code = bean.getCode();
        LogUtils.i(String.valueOf(code), TAG);
        if (code == 200) {
            mPresenter.getNewFriendMessage(UserInfoBean.getUid(mContext));
        }
    }

    @Override
    public void getAgree(CommonBean bean, final String fromId) {
        int code = bean.getCode();
        LogUtils.i(String.valueOf(code), TAG);
        if (code == 200) {
            mPresenter.getNewFriendMessage(UserInfoBean.getUid(mContext));
            // 以单聊类型为例
            SessionTypeEnum sessionType = SessionTypeEnum.P2P;
            String text = "我们已经是好友啦，快和新朋友打个招呼吧！";
            // 创建一个文本消息
            IMMessage textMessage = MessageBuilder.createTextMessage(fromId, sessionType, text);
            // 发送给对方
            NIMClient.getService(MsgService.class).sendMessage(textMessage, false);
        } else if (code == 407) {
            initPresenter();
            showShortText("对方已经是您的好友");
        }
    }
}
